<template>
	<zh-form ref="userCellphoneFormRef" :span="24" :model="state.form" :rules="state.rules">
		<zh-form-input prop="userName" label="账号" v-model="state.form.userName" :disabled="true"></zh-form-input>
		<zh-form-input prop="fullName" label="账号名称" v-model="state.form.fullName" :disabled="true"></zh-form-input>
		<zh-form-input prop="cellphone" label="手机号码" v-model="state.form.cellphone"></zh-form-input>
		<zh-form-item prop="shortMsgCode" label="手机验证码">
			<el-col :span="17">
				<el-input type="text" maxlength="6" placeholder="请输入手机验证码" v-model="state.form.shortMsgCode" clearable autocomplete="off"> </el-input>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="6">
				<el-button type="primary" :disabled="state.disableCodeBtn" @click="sendMessage(userCellphoneFormRef)" class="login-content-code">{{
					(!state.msgForm.smsSendBtn && state.msgForm.smsText) || state.msgForm.time + ' s'
				}}</el-button>
			</el-col>
		</zh-form-item>
    <zh-form-item class="login-animation3" prop="sliderPosition" label="图形验证码">
      <div ref="captchaImageContainer"  class="captcha-container" style="width: 310px;">
        <div class="captcha-image-container" @mousedown="startDrag" @touch-start="startDrag">
          <img :src="state.originalImgSrc" alt="拼图验证码" class="captcha-bg" />
          <img :src="state.sliderImgSrc" alt="滑块" class="slider" :style="{ left: state.sliderPosition + 'px' }" />
        </div>
        <el-slider
            style="padding: 15px"
            v-model="state.sliderPosition"
            :max="captchaImageContainer?.offsetWidth || 310"
            :show-tooltip="false"
            :input-size="'small'"
        />
      </div>
    </zh-form-item>
	</zh-form>
</template>

<script lang="ts" setup name="PersonPasswordForm">
import { ElMessage } from 'element-plus';
import validate from '@/utils/validate';
import {ref} from "vue";
//------------------接收传入参数(组件)-------------------
const props = defineProps({
	userInfo: {
		type: Object,
		default: () => {},
		required: false,
	},
	modelValue: Boolean,
});
const checkPhone = (rule: any, value: any, callback: any) => {
	if (!value) {
		return callback(new Error('请输入的手机号码！'));
	}
	if (!validate.isPhone(state.form.cellphone)) {
		callback(new Error('请输入正确的手机号码'));
	} else {
		callback();
	}
};
//------------------定义子组件---------------------------
const emit = defineEmits(['update:modelValue']);
const userCellphoneFormRef = ref<any>({});
let interval: any = null;
//------------------内部变量定义-------------------------
const state = reactive({
	rules: reactive({
		cellphone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
		imgCode: [
			{
				required: true,
				message: '图片验证码不能为空',
				trigger: 'blur',
			},
		],
		shortMsgCode: [
			{
				required: true,
				message: '短信验证码不能为空',
				trigger: 'change',
			},
		],
	}),
	userTypeDisabled: true,
	dictData: {} as any,
	form: props.userInfo,
	disableCodeBtn: false,
	msgForm: {
		time: 60,
		loginBtn: false,
		smsSendBtn: false,
		smsText: '获取验证码',
	},
  originalImgSrc: '',
  sliderImgSrc: '',
  sliderPosition: 0,
  isDragging: false,
  startX: 0,
  startSliderPosition: 0,
	loading: {
		signIn: false,
	},
	category: 'JIGSAW',
});
let loginKey = ref('');
const captchaImageContainer = ref<HTMLElement | null>(null);

//------------------定义调用方法-------------------------

// 开始拖拽
const startDrag = (event) => {
  state.isDragging = true;
  state.startX = event.type === 'touchstart' ? event.touches[0].clientX : event.clientX;
  state.startSliderPosition = state.sliderPosition;
  document.addEventListener(event.type === 'touchstart' ? 'touchmove' : 'mousemove', doDrag);
  document.addEventListener(event.type === 'touchstart' ? 'touchend' : 'mouseup', stopDrag);
};

// 拖拽中
const doDrag = (event) => {
  if (!state.isDragging) return;

  const currentX = event.type === 'touchmove' ? event.touches[0].clientX : event.clientX;
  const diffX = currentX - state.startX;
  const maxPosition = document.querySelector('.captcha-bg').width - 50; // 滑块宽度假设为50px

  state.sliderPosition = Math.min(maxPosition, Math.max(0, state.startSliderPosition + diffX));
};

// 停止拖拽
const stopDrag = (event) => {
  if (!state.isDragging) return;
  state.isDragging = false;
  document.removeEventListener(event.type === 'touchend' ? 'touchmove' : 'mousemove', doDrag);
  document.removeEventListener(event.type === 'touchend' ? 'touchend' : 'mouseup', stopDrag);
};

const getCode = () => {
	let params = { category: state.category };
	$api.common.send
		.postCrypto('login0004', params)
		.then((res) => {
			let result = res.result;
			loginKey.value = result.loginKey;
      state.originalImgSrc = result.originalImageBase64;
      state.sliderImgSrc = result.sliderImageBase64;
		})
		.catch(() => {});
};

async function saveCellphone() {
	//校验表单
	let checkFlag = await userCellphoneFormRef.value.checkForm();
	if (checkFlag) {
		const params = state.form;
		let ret = null as any;
		if (params.userId) {
			ret = await $api.common.send.postCrypto('user0011', params);
			if (ret.code === 0) {
				emit('update:modelValue', false);
				ElMessage.success('修改成功！');
			}
		}
		return ret;
	}
	return null;
}
const sendMessage = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	if (state.disableCodeBtn) {
		return;
	}
	let fieldsToValidate = ['cellphone'];
	Promise.all(
		fieldsToValidate.map((item: string) => {
			return new Promise((resolve) => {
				formEl.validateField(item, (valid) => {
					resolve(valid);
				});
			});
		})
	).then((valids) => {
		let m = valids.filter((valid) => !valid).length > 0;
		if (!m) {
			state.disableCodeBtn = true;

			interval = window.setInterval(() => {
				if (state.msgForm.time-- <= 0) {
					state.msgForm.time = 60;
					state.disableCodeBtn = false;
					state.msgForm.smsSendBtn = false;
					state.msgForm.smsText = '重新发送';
					window.clearInterval(interval);
					getCode();
				}
			}, 1000);
			let params = {
				loginKey: loginKey.value,
				category: state.category,
				loginType: state.loginType,
				cellphone: state.form.cellphone,
				userId: state.form.userId,
				equipmentType: 'pc',
				smsSendType: 'editCellphone',
			};
			$api.common.send
				.postCrypto('login0005', params, null, true)
				.then(() => {
					ElMessage.success('短信发送成功');
					state.disableCodeBtn = true;
					state.msgForm.smsSendBtn = true;
				})
				.catch(() => {
					window.clearInterval(interval);
					state.msgForm.time = 60;
					state.disableCodeBtn = false;
					state.msgForm.smsSendBtn = false;
					state.msgForm.smsText = '获取验证码';
				});
		}
	});
};
//------------------初始化------------------------------

// 数据字典初始化
const params = {} as any;
params.dictFields = 'userType,sex,cardType';
$api.common.getBatchDict.post(params).then((res) => {
	state.dictData = res.result;
});
getCode();
watch(
	() => props.userInfo,
	(val) => {
		state.form = val;
	}
);
onDeactivated(() => {
	if (interval) {
		window.clearInterval(interval);
	}
});
//------------设置给父组件调用的数据/方法(组件)-----------
defineExpose({ form: state.form, saveCellphone });
</script>
<style scoped lang="scss">
.login-img-code {
	display: block;
	width: 100%;
	height: 40px;
}
.login-content-code {
	width: 100%;
	padding: 0;
}

.captcha-container {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  position: relative;
}

.captcha-image-container {
  position: relative;
  width: 100%;
  cursor: pointer;
}

.captcha-bg {
  width: 100%;
  height: auto;
}

.slider {
  position: absolute;
  top: 0;
  left: 0;
  width: auto;
  height: auto;
  cursor: grab;
  cursor: -webkit-grab;
}
</style>
